package com.qf.fronted.controller;

import com.qf.admin.domain.User;
import com.qf.commons.Data;
import com.qf.fronted.service.IUserService;
import com.qf.pojo.ImageCode;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RequestMapping(value = "/login", name = "FrontedLoginServlet")
@CrossOrigin
@RestController
public class LoginController {


    private IUserService userServiceImpl;

    public LoginController(IUserService userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }

    @PostMapping
    public Data checkUsernameAndPassword(String username,String password, String validateCode,HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Data data = null;
        HttpSession session = req.getSession();
        ImageCode imageCode = (ImageCode) session.getAttribute("imageCode");
      // 当验证码过期或者绕开前端页面
       /* if (null == imageCode) {
            data = new Data(-2, "验证码已过期，请刷新！");
            //刷新页面
            resp.setHeader("refresh", "0");
           return data;

        }

        if (null == validateCode || "".equals(validateCode.trim()) ||
                validateCode.length() != 4 || imageCode.isExpired() || !validateCode.equals(imageCode.getCode())) {

            data = new Data(0, "验证码错误！");
            //刷新页面
            resp.setHeader("refresh", "0");
            return data;

        }

     // 如果代码走到这里表示验证码正确，那么就验证码清除掉，避免内存占用过大
        session.removeAttribute("validateCode");*/
        User user = userServiceImpl.checkUsernameAndPassword(username, DigestUtils.md5Hex(password));
        if (null != user) {  //用户名密码正确，放到session中
            session.setAttribute("user", user);
//            session.setAttribute("uId",user.getId());
            Cookie cookie = new Cookie("uId",user.getId().toString());
            cookie.setMaxAge(1*24*3600);
            resp.addCookie(cookie);
            data = new Data(1, "success");
        } else { //用户名密码错误
            data = new Data(-1, "用户名或密码错误");
        }
        return data;

    }
}
